package com.hz.foodstalls.controller;

import com.hz.foodstalls.model.WechatRobotMedia;
import org.apache.commons.lang3.StringUtils;

import com.jfinal.plugin.activerecord.Page;

import com.hz.foodstalls.interceptor.AdminInterceptor;

import com.hz.foodstalls.controller.BaseController;

import com.jfinal.aop.Before;import com.jfinal.ext.route.ControllerBind;
import java.util.HashMap;
import java.util.Map;
import com.hz.foodstalls.model.WechatRobot;

import com.hz.foodstalls.validator.WechatRobotValidator;

/**
 * WechatRobotController, Generated by Robot on 2017-8-25 15:39:45.
 */
@Before(AdminInterceptor.class)
@ControllerBind(controllerKey = "/wechatrobot", viewPath = "/WEB-INF/views/wechatrobot/")
public class WechatRobotController extends BaseController {

	private final String MODULE_NAME = "/wechatrobot";


	public void index() {
		String id = getPara("id");
		Page<WechatRobot> page = WechatRobot.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10),id);
		setAttr("page", page);
		setAttr("id",id);
		render("index.html");
	}

	@Before(WechatRobotValidator.class)
	public void save() {
		WechatRobot model = getModel(WechatRobot.class, "wechatRobot");
		boolean isSave = model.getId() == null;

		if (WechatRobot.dao.saveOrUpdate(model, isSave)){
			redirect(MODULE_NAME+"/edit?id="+model.getId()+"&wxid="+model.getWechatInfoId());
		}


		else
			renderError(501);
	}

	public void edit() {
		int wechat_info_id=Integer.parseInt(getPara("wxid"));
		WechatRobot wechatRobot = WechatRobot.dao.findById(getParaToInt("id",0));
		if (wechatRobot == null)
			wechatRobot = new WechatRobot();
		wechatRobot.put("wechat_info_id",wechat_info_id);

		setAttr("wechatRobot", wechatRobot);
		//
		if(wechatRobot.getId()!=null){
			Page<WechatRobotMedia> page = WechatRobotMedia.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10),wechatRobot.getId().toString());
			setAttr("page", page);
		}else{
			Page<WechatRobotMedia> page = WechatRobotMedia.dao.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10),"0");
			setAttr("page", page);
		}


		render("edit.html");
	}

	public void delete() {
		String ids = StringUtils.join(getParaValues("ids"), ",");
		int ret = WechatRobot.dao.batchDelete(ids);
		if (ret>0) {
			ajaxJsonSuccessMessage("删除成功!");
		} else {
			ajaxJsonErrorMessage("删除失败！");
		}
	}

	private String indexTitle = "微信自动回复管理";
	private String editTitle = "编辑";

	public Map<String,String> getPageTitleBread() {
		Map<String,String> pageTitleBread = new HashMap<String,String>();
		pageTitleBread.put("indexTitle", indexTitle);
		pageTitleBread.put("editTitle", editTitle);
		return pageTitleBread;
	}
}
